<template>
  <div class="user-permission-management">
    <a-page-header 
      title="用户权限管理" 
      @back="goBack"
    />
    
    <a-tabs v-model:activeKey="activeTab" class="tabs">
      <a-tab-pane key="users" tab="用户管理">
        <div class="tab-content">
          <div class="controls">
            <a-button type="primary" @click="handleAddUser" v-if="userPermissionStore.isSystemAdmin">新增用户</a-button>
            <a-button @click="refreshUsers">刷新</a-button>
          </div>
          
          <a-table :data-source="userPermissionStore.users" :columns="userColumns" :loading="loading" :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag :color="getUserStatusColor(record.status)">
                  {{ getUserStatusText(record.status) }}
                </a-tag>
              </template>
              <template v-else-if="column.dataIndex === 'role'">
                <a-tag :color="getUserRoleColor(record.role)">
                  {{ getUserRoleText(record.role) }}
                </a-tag>
              </template>
              <template v-else-if="column.dataIndex === 'action'">
                <a-button size="small" @click="handleEditUser(record)">编辑</a-button>
                <a-button 
                  size="small" 
                  danger 
                  @click="handleDeleteUser(record)" 
                  v-if="userPermissionStore.isSystemAdmin && userPermissionStore.currentUser.id !== record.id"
                >
                  删除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>
      </a-tab-pane>
      
      <a-tab-pane key="familyTrees" tab="家族树权限">
        <div class="tab-content">
          <div class="controls">
            <a-select 
              v-model:value="selectedFamilyTree" 
              placeholder="选择家族树" 
              @change="loadFamilyTreeUsers"
              style="width: 300px; margin-right: 20px;"
            >
              <a-select-option
                v-for="tree in familyTrees"
                :key="tree.id"
                :value="tree.id"
              >
                {{ tree.name }}
              </a-select-option>
            </a-select>
            
            <a-button type="primary" @click="handleAddUserToFamilyTree" v-if="userPermissionStore.isSystemAdmin || canManageSelectedFamilyTree">添加成员</a-button>
            <a-button @click="refreshFamilyTreeUsers">刷新</a-button>
          </div>
          
          <a-table :data-source="userPermissionStore.familyTreeUsers" :columns="familyTreeUserColumns" :loading="loading" :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'role'">
                <a-tag :color="getFamilyRoleColor(record.role)">
                  {{ getFamilyRoleText(record.role) }}
                </a-tag>
              </template>
              <template v-else-if="column.dataIndex === 'action'">
                <a-button 
                  size="small" 
                  @click="handleEditFamilyUserRole(record)"
                  v-if="userPermissionStore.isSystemAdmin || canManageSelectedFamilyTree"
                >
                  编辑角色
                </a-button>
                <a-button 
                  size="small" 
                  danger 
                  @click="handleRemoveUserFromFamilyTree(record)" 
                  v-if="userPermissionStore.isSystemAdmin || canManageSelectedFamilyTree"
                >
                  移除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>
      </a-tab-pane>
    </a-tabs>
    
    <!-- 用户编辑对话框 -->
    <a-modal v-model:open="userDialogVisible" :title="editingUser.id ? '编辑用户' : '新增用户'" width="50%">
      <a-form :model="editingUser" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="用户名" v-if="!editingUser.id">
          <a-input v-model:value="editingUser.username" />
        </a-form-item>
        <a-form-item label="昵称">
          <a-input v-model:value="editingUser.nickname" />
        </a-form-item>
        <a-form-item label="邮箱">
          <a-input v-model:value="editingUser.email" />
        </a-form-item>
        <a-form-item label="手机号">
          <a-input v-model:value="editingUser.phone" />
        </a-form-item>
        <a-form-item label="状态" v-if="userPermissionStore.isSystemAdmin">
          <a-select v-model:value="editingUser.status" style="width: 100%">
            <a-select-option :value="0">正常</a-select-option>
            <a-select-option :value="1">禁用</a-select-option>
            <a-select-option :value="2">锁定</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="角色" v-if="userPermissionStore.isSystemAdmin">
          <a-select v-model:value="editingUser.role" style="width: 100%">
            <a-select-option value="ADMIN">管理员</a-select-option>
            <a-select-option value="USER">普通用户</a-select-option>
            <a-select-option value="GUEST">访客</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      
      <template #footer>
        <a-button @click="userDialogVisible = false">取消</a-button>
        <a-button type="primary" @click="saveUser">保存</a-button>
      </template>
    </a-modal>
    
    <!-- 家族树用户角色编辑对话框 -->
    <a-modal v-model:open="familyRoleDialogVisible" title="编辑家族树角色" width="40%">
      <a-form :model="editingFamilyUserRole" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="用户名">
          <a-input v-model:value="editingFamilyUserRole.user.username" disabled />
        </a-form-item>
        <a-form-item label="角色">
          <a-select v-model:value="editingFamilyUserRole.role" style="width: 100%">
            <a-select-option value="CREATOR">创建者</a-select-option>
            <a-select-option value="ADMIN">管理员</a-select-option>
            <a-select-option value="EDITOR">编辑者</a-select-option>
            <a-select-option value="VIEWER">查看者</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      
      <template #footer>
        <a-button @click="familyRoleDialogVisible = false">取消</a-button>
        <a-button type="primary" @click="saveFamilyUserRole">保存</a-button>
      </template>
    </a-modal>
    
    <!-- 添加用户到家族树对话框 -->
    <a-modal v-model:open="addUserToFamilyDialogVisible" title="添加用户到家族树" width="50%">
      <a-form :model="newFamilyUser" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="用户">
          <a-select 
            v-model:value="newFamilyUser.userId" 
            placeholder="请选择用户" 
            style="width: 100%"
            show-search
          >
            <a-select-option
              v-for="user in availableUsers"
              :key="user.id"
              :value="user.id"
            >
              {{ user.username }} ({{ user.nickname }})
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="角色">
          <a-select v-model:value="newFamilyUser.role" style="width: 100%">
            <a-select-option value="CREATOR">创建者</a-select-option>
            <a-select-option value="ADMIN">管理员</a-select-option>
            <a-select-option value="EDITOR">编辑者</a-select-option>
            <a-select-option value="VIEWER">查看者</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      
      <template #footer>
        <a-button @click="addUserToFamilyDialogVisible = false">取消</a-button>
        <a-button type="primary" @click="addUserToFamilyTree">添加</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { ref, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { useUserPermissionStore } from '../stores/userPermission'
import api from '../api'

export default {
  name: 'UserPermissionManagement',
  setup() {
    const router = useRouter()
    const userPermissionStore = useUserPermissionStore()
    const activeTab = ref('users')
    const selectedFamilyTree = ref('')
    const familyTrees = ref([])
    const userDialogVisible = ref(false)
    const familyRoleDialogVisible = ref(false)
    const addUserToFamilyDialogVisible = ref(false)
    const canManageSelectedFamilyTree = ref(false)
    const loading = ref(false)
    
    const editingUser = ref({
      id: null,
      username: '',
      nickname: '',
      email: '',
      phone: '',
      status: 0,
      role: 'USER'
    })
    
    const editingFamilyUserRole = ref({
      id: null,
      user: {},
      role: ''
    })
    
    const newFamilyUser = ref({
      userId: null,
      familyTreeId: null,
      role: 'VIEWER'
    })
    
    const availableUsers = ref([])
    
    // 使用 useRequest 获取用户列表
    const { loading: fetchLoading, refetch: fetchUsers } = userPermissionStore.useFetchUsers()
    
    // 更新加载状态
    watch(fetchLoading, (newVal) => {
      loading.value = newVal.value
    })
    
    // 表格列定义
    const userColumns = [
      {
        title: 'ID',
        dataIndex: 'id',
        width: 80
      },
      {
        title: '用户名',
        dataIndex: 'username',
        width: 120
      },
      {
        title: '昵称',
        dataIndex: 'nickname',
        width: 120
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        width: 150
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        width: 120
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 100
      },
      {
        title: '角色',
        dataIndex: 'role',
        width: 100
      },
      {
        title: '操作',
        dataIndex: 'action',
        width: 200
      }
    ]
    
    const familyTreeUserColumns = [
      {
        title: '用户名',
        dataIndex: 'user.username',
        width: 120
      },
      {
        title: '昵称',
        dataIndex: 'user.nickname',
        width: 120
      },
      {
        title: '邮箱',
        dataIndex: 'user.email',
        width: 150
      },
      {
        title: '角色',
        dataIndex: 'role',
        width: 120
      },
      {
        title: '操作',
        dataIndex: 'action',
        width: 200
      }
    ]
    
    // 获取家族树列表
    const getFamilyTrees = async () => {
      try {
        loading.value = true
        const response = await api.get('/family-trees')
        familyTrees.value = response.data.data || []
      } catch (error) {
        message.error('获取家族树列表失败')
        console.error('获取家族树列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 加载家族树用户
    const loadFamilyTreeUsers = async (familyTreeId) => {
      if (!familyTreeId) return
      
      userPermissionStore.setSelectedFamilyTree(familyTreeId)
      
      try {
        loading.value = true
        const { refetch: fetchFamilyTreeUsers } = userPermissionStore.useFetchFamilyTreeUsers()
        const result = await fetchFamilyTreeUsers(familyTreeId)
        if (!result?.data?.data) {
          message.error(result?.data?.msg || '加载家族树用户失败')
        }
        
        // 检查当前用户是否可以管理该家族树
        try {
          const permissionResponse = await api.get(`/permissions/family-tree/${familyTreeId}/manage`)
          canManageSelectedFamilyTree.value = permissionResponse.data.data || false
        } catch (error) {
          canManageSelectedFamilyTree.value = false
        }
      } catch (error) {
        message.error('加载家族树用户失败')
        console.error('加载家族树用户失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 获取可用用户列表（排除已在当前家族树中的用户）
    const getAvailableUsers = async () => {
      try {
        const response = await api.get('/users')
        const allUsers = response.data.data || []
        
        // 获取当前家族树中的用户
        const familyTreeUsersResponse = await api.get(`/user-family/family-tree/${selectedFamilyTree.value}`)
        const familyTreeUserIds = (familyTreeUsersResponse.data.data || []).map(item => item.user.id)
        
        // 过滤掉已在当前家族树中的用户
        availableUsers.value = allUsers.filter(user => !familyTreeUserIds.includes(user.id))
      } catch (error) {
        message.error('获取用户列表失败')
        console.error('获取用户列表失败:', error)
      }
    }
    
    // 刷新用户列表
    const refreshUsers = async () => {
      try {
        loading.value = true
        const result = await fetchUsers()
        if (result?.data?.code !== 200) {
          message.error(result?.data?.msg || '刷新用户列表失败')
        }
      } catch (error) {
        message.error('刷新用户列表失败')
        console.error('刷新用户列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 刷新家族树用户列表
    const refreshFamilyTreeUsers = async () => {
      if (selectedFamilyTree.value) {
        await loadFamilyTreeUsers(selectedFamilyTree.value)
      }
    }
    
    // 处理添加用户
    const handleAddUser = () => {
      editingUser.value = {
        id: null,
        username: '',
        nickname: '',
        email: '',
        phone: '',
        status: 0,
        role: 'USER'
      }
      userDialogVisible.value = true
    }
    
    // 处理编辑用户
    const handleEditUser = (record) => {
      editingUser.value = { ...record }
      userDialogVisible.value = true
    }
    
    // 保存用户
    const saveUser = async () => {
      try {
        loading.value = true
        let result
        
        if (editingUser.value.id) {
          // 更新用户
          const { mutateAsync: updateUser } = userPermissionStore.useUpdateUser()
          result = await updateUser(editingUser.value.id, editingUser.value)
        } else {
          // 创建用户
          const { mutateAsync: createUser } = userPermissionStore.useCreateUser()
          result = await createUser(editingUser.value)
        }
        
        if (result?.data?.code === 200) {
          message.success(editingUser.value.id ? '用户更新成功' : '用户创建成功')
          userDialogVisible.value = false
          await refreshUsers()
        } else {
          message.error(result?.data?.msg || (editingUser.value.id ? '用户更新失败' : '用户创建失败'))
        }
      } catch (error) {
        message.error(editingUser.value.id ? '用户更新失败' : '用户创建失败')
        console.error('操作失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 处理删除用户
    const handleDeleteUser = (record) => {
      Modal.confirm({
        title: '确认删除',
        content: `确定要删除用户 "${record.username}" 吗？此操作不可恢复！`,
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          try {
            const { mutateAsync: deleteUser } = userPermissionStore.useDeleteUser()
            const result = await deleteUser(record.id)
            if (result?.data?.code === 200) {
              message.success('用户删除成功')
              await refreshUsers()
            } else {
              message.error(result?.data?.msg || '用户删除失败')
            }
          } catch (error) {
            message.error('用户删除失败')
            console.error('删除失败:', error)
          }
        }
      })
    }
    
    // 处理编辑家族树用户角色
    const handleEditFamilyUserRole = (record) => {
      editingFamilyUserRole.value = { ...record }
      familyRoleDialogVisible.value = true
    }
    
    // 保存家族树用户角色
    const saveFamilyUserRole = async () => {
      try {
        loading.value = true
        const { mutateAsync: updateUserFamilyRole } = userPermissionStore.useUpdateUserFamilyRole()
        const result = await updateUserFamilyRole(
          editingFamilyUserRole.value.id,
          editingFamilyUserRole.value.role
        )
        
        if (result?.data?.code === 200) {
          message.success('角色更新成功')
          familyRoleDialogVisible.value = false
          await refreshFamilyTreeUsers()
        } else {
          message.error(result?.data?.msg || '角色更新失败')
        }
      } catch (error) {
        message.error('角色更新失败')
        console.error('更新失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 处理添加用户到家族树
    const handleAddUserToFamilyTree = () => {
      newFamilyUser.value = {
        userId: null,
        familyTreeId: selectedFamilyTree.value,
        role: 'VIEWER'
      }
      addUserToFamilyDialogVisible.value = true
    }
    
    // 添加用户到家族树
    const addUserToFamilyTree = async () => {
      try {
        loading.value = true
        const { mutateAsync: addUserToFamily } = userPermissionStore.useAddUserToFamily()
        const result = await addUserToFamily(newFamilyUser.value)
        
        if (result?.data?.code === 200) {
          message.success('用户添加成功')
          addUserToFamilyDialogVisible.value = false
          await refreshFamilyTreeUsers()
        } else {
          message.error(result?.data?.msg || '用户添加失败')
        }
      } catch (error) {
        message.error('用户添加失败')
        console.error('添加失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 处理从家族树移除用户
    const handleRemoveUserFromFamilyTree = (record) => {
      Modal.confirm({
        title: '确认移除',
        content: `确定要将用户 "${record.user.username}" 从当前家族树中移除吗？`,
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          try {
            const { mutateAsync: removeUserFromFamily } = userPermissionStore.useRemoveUserFromFamily()
            const result = await removeUserFromFamily(record.id)
            if (result?.data?.code === 200) {
              message.success('用户移除成功')
              await refreshFamilyTreeUsers()
            } else {
              message.error(result?.data?.msg || '用户移除失败')
            }
          } catch (error) {
            message.error('用户移除失败')
            console.error('移除失败:', error)
          }
        }
      })
    }
    
    // 获取用户状态颜色
    const getUserStatusColor = (status) => {
      switch (status) {
        case 0: return 'green'
        case 1: return 'red'
        case 2: return 'orange'
        default: return 'default'
      }
    }
    
    // 获取用户状态文本
    const getUserStatusText = (status) => {
      switch (status) {
        case 0: return '正常'
        case 1: return '禁用'
        case 2: return '锁定'
        default: return '未知'
      }
    }
    
    // 获取用户角色颜色
    const getUserRoleColor = (role) => {
      switch (role) {
        case 'ADMIN': return 'red'
        case 'USER': return 'blue'
        case 'GUEST': return 'default'
        default: return 'default'
      }
    }
    
    // 获取用户角色文本
    const getUserRoleText = (role) => {
      switch (role) {
        case 'ADMIN': return '管理员'
        case 'USER': return '用户'
        case 'GUEST': return '访客'
        default: return '未知'
      }
    }
    
    // 获取家族角色颜色
    const getFamilyRoleColor = (role) => {
      switch (role) {
        case 'CREATOR': return 'red'
        case 'ADMIN': return 'orange'
        case 'EDITOR': return 'blue'
        case 'VIEWER': return 'default'
        default: return 'default'
      }
    }
    
    // 获取家族角色文本
    const getFamilyRoleText = (role) => {
      switch (role) {
        case 'CREATOR': return '创建者'
        case 'ADMIN': return '管理员'
        case 'EDITOR': return '编辑者'
        case 'VIEWER': return '查看者'
        default: return '未知'
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }
    
    // 初始化
    onMounted(async () => {
      const { refetch: fetchCurrentUser } = userPermissionStore.useFetchCurrentUser()
      const userResult = await fetchCurrentUser()
      if (userResult?.data?.code === 200) {
        await refreshUsers()
        await getFamilyTrees()
      } else {
        message.error(userResult?.data?.msg || '获取用户信息失败')
      }
    })
    
    return {
      userPermissionStore,
      activeTab,
      selectedFamilyTree,
      familyTrees,
      userDialogVisible,
      editingUser,
      familyRoleDialogVisible,
      addUserToFamilyDialogVisible,
      canManageSelectedFamilyTree,
      editingFamilyUserRole,
      newFamilyUser,
      availableUsers,
      loading,
      userColumns,
      familyTreeUserColumns,
      refreshUsers,
      refreshFamilyTreeUsers,
      handleAddUser,
      handleEditUser,
      saveUser,
      handleDeleteUser,
      handleEditFamilyUserRole,
      saveFamilyUserRole,
      handleAddUserToFamilyTree,
      addUserToFamilyTree,
      handleRemoveUserFromFamilyTree,
      loadFamilyTreeUsers,
      getUserStatusColor,
      getUserStatusText,
      getUserRoleColor,
      getUserRoleText,
      getFamilyRoleColor,
      getFamilyRoleText,
      goBack
    }
  }
}
</script>

<style scoped>
.user-permission-management {
  padding: 20px;
}

.tabs {
  margin-top: 20px;
}

.tab-content {
  padding: 20px 0;
}

.controls {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
</style>